package com.xiaorun.portal.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.xiaorun.portal.config.QiNiuConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/****
 *
 * @Description: 七牛图床操作类
 * @author boyiis
 * @date 2018年11月17日 下午5:55:49
 */
@Slf4j
@Component
public class QiNiuImgUpload {

    @Autowired
    private QiNiuConfig qiNiuConfig;

    /**
     * 简单上传的凭证
     *
     * @return
     */
    public String getUpToken() {
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        return auth.uploadToken(qiNiuConfig.getBucket());
    }

    /**
     * 覆盖上传的凭证
     *
     * @param key 覆盖的文件名称
     * @return
     */
    public String getUpToken(String key) {
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        String upToken = auth.uploadToken(qiNiuConfig.getBucket(), key);
        return upToken;
    }


    /**
     * 字节数组上传
     *
     * @param b
     * @param fileName
     * @return
     */
    public Response upload(byte[] b, String fileName, boolean override) {
        return upload(b, fileName, Zone.huanan(), override);
    }


    /**
     * 字节数组上传
     *
     * @param b
     * @param fileName
     * @param zone
     * @param override 是否覆盖上传, 如果为覆盖上传fileName要跟原来的文件名一样
     * @return
     */
    public Response upload(byte[] b, String fileName, Zone zone, boolean override) {
        Configuration cfg = new Configuration(zone);
        UploadManager uploadManager = new UploadManager(cfg);
        String token = override ? getUpToken(fileName) : getUpToken();
        Response res = null;
        try {
            //调用put方法上传
            res = uploadManager.put(b, fileName, token);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            log.debug(putRet.key);
            log.debug(putRet.hash);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            log.error(r.toString());
            try {
                //响应的文本信息
                log.error(r.bodyString());
            } catch (QiniuException e1) {
                log.info("解析七牛上传响应文本失败");
            }
        }
        return res;
    }

    /**
     * 流上传
     *
     * @param b
     * @param fileName
     * @param zone
     * @param override 是否覆盖上传, 如果为覆盖上传fileName要跟原来的文件名一样
     * @return
     */
    public Response uploadByStream(byte[] b, String fileName, Zone zone, boolean override) {
        Configuration cfg = new Configuration(zone);
        UploadManager uploadManager = new UploadManager(cfg);
        String token = override ? getUpToken(fileName) : getUpToken();

        Response res = null;
        try {
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(b);
            //调用put方法上传
            res = uploadManager.put(byteInputStream, fileName, token, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            log.debug(putRet.key);
            log.debug(putRet.hash);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            log.error(r.toString());
            try {
                //响应的文本信息
                log.error(r.bodyString());
            } catch (QiniuException e1) {
                log.info("解析七牛上传响应文本失败");
            }
        }
        return res;
    }

    /**
     * Upload img.
     *
     * @param file the file
     */
    public String uploadImg(MultipartFile file){
        try{
            return uploadImg(file.getBytes());
        }catch (Exception e){
            log.error("上传图片出错", e);
        }
        return null;
    }

    /**
     * Upload img字节数组上传
     *
     * @param b
     * @return
     */
    public String uploadImg(byte[] b) {
        try{
            String fileName = System.currentTimeMillis() + "_zch.jpg";
            Response response = upload(b, fileName, false);
            if (response.statusCode == 200) {
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                log.debug("key:{},  hash:{}",putRet.key, putRet.hash);
                return qiNiuConfig.getDomain() + "/" + putRet.key;
            }
        }catch (Exception e){
            log.error("上传图片出错", e);
        }
        return null;
    }


}
